define(['./../../initial', './../../service/mapInstance', './../../service/renderPointsOnMap', './../../service/toggleSideBar', './../../service/viewMode', './../../service/chartsFactory'], function() {

    var app = angular.module('App.home');

    app.factory('webSocketReceiver', ['$rootScope', '$filter', '$timeout', 'mapInstance', 'renderPointsOnMap', 'toggleSideBar', 'viewMode', 'chartsFactory', '$q', 'bufferCaller',
        function($rootScope, $filter, $timeout, mapInstance, renderPointsOnMap, toggleSideBar, viewMode, chartsFactory, $q, bufferCaller) {

            function showMsg(msg) {
                var defer = $q.defer();
                var h = document.getElementById('autoSurveyMsg');
                if (!h) {
                    var content = $('#singleChartModalCotent').empty();
                    h = document.createElement('h1');
                    h.id = 'autoSurveyMsg';
                    h.innerHTML = msg;
                    content[0].appendChild(h);
                } else {
                    h.innerHTML = msg;
                }
                var modal = $('#singleChartModal')
                    .modal({
                        onVisible: function() {}
                    }).modal('show');
                $timeout((function(modal) {
                    return function() {
                        modal.modal('hide');
                        defer.resolve();
                    };
                })(modal), 1500);
                return defer.promise;
            }

            var receiver = {
                tempPoint: null,
                buffer: bufferCaller(),
                initial: function() {

                    function checkPrjActive(data) { //查看该自动化观测项目是否被激活,并且地图是否处于active模式
                        var map = mapInstance.getMap();
                        if (map.viewState === 'active' && map.autoSurveyPrjName === data.Target) {
                            return true;
                        } else return false;
                    }

                    $rootScope.Socket = io.connect('/');

                    $rootScope.Socket.on('GetProjects', function(prjList) {
                        var onlinePrjNames = prjList;
                        var prj = $rootScope.curPrj;
                        prj.monitorPoints.forEach(function(mpts) {
                            mpts.locationPoints.forEach(function(lpts) {
                                if (lpts.isAutoSurveyPrj) {
                                    var autoPrjName = lpts.autoSurveyPrjName;
                                    if (onlinePrjNames && onlinePrjNames.indexOf(autoPrjName) >= 0) {
                                        lpts.autoSurveyPrjOnline = true;
                                    }
                                }
                            });
                        });
                    });

                    $rootScope.Socket.on('StartSurvey', function(data) {
                        if (checkPrjActive(data)) {
                            receiver.buffer.add(function() {
                                showMsg('测量指令已下达...');
                            });
                        }
                    });
                    $rootScope.Socket.on('StopSurvey', function(data) {
                        if (checkPrjActive(data)) {
                            receiver.buffer.cancel();
                            showMsg('测量已终止..');
                        }
                    });



                    $rootScope.Socket.on('MeasurePoint', function(data) {
                        if (checkPrjActive(data)) {
                            var autoSurveyPoint = $rootScope.curPrj.findAutoSurveyPoint(viewMode.monitorType, viewMode.location, data.PointName);
                            if (autoSurveyPoint) {
                                receiver.tempPoint = autoSurveyPoint;

                                receiver.buffer.add((function(autoSurveyPoint) {
                                    return function() {
                                        toggleSideBar.toggleBottomSideBar('hide').then(function() {
                                            renderPointsOnMap(autoSurveyPoint, true);
                                        });
                                    };
                                })(autoSurveyPoint));
                            }
                        }
                    });

                    $rootScope.Socket.on('MeasureValue', function(data) {
                        if (checkPrjActive(data) && data.Valid && receiver.tempPoint && receiver.tempPoint.deviceNo === data.PointName) {
                            var recentData = $.extend(data.Data, receiver.tempPoint);
                            receiver.buffer.add((function(recentData) {
                                return function() {
                                    toggleSideBar.toggleBottomSideBar('show').then(function() {
                                        chartsFactory.createAutoSurveyOnePointRecentValues('#chart', recentData);
                                    });
                                };
                            })(recentData));
                        }
                    });

                    //测量完成
                    $rootScope.Socket.on('SurveyComplete', function(data) {
                        if (checkPrjActive(data)) {

                            var lastResult = data.LastResult;
                            //*****lastResult format [name,ringNumber,startTime,endTime,value]
                            var map = mapInstance.getMap();
                            receiver.buffer.add((function(lastResult, map) {
                                return function() {
                                    map.clearPointsLayer();
                                    toggleSideBar.toggleBottomSideBar('hide').then(function() {
                                        return showMsg('测量完成...');
                                    }).then(function() {
                                        return toggleSideBar.toggleBottomSideBar('show');
                                    }).then(function() {
                                        return chartsFactory.createAutoSurveyAllLastValues('#chart', lastResult);
                                    });
                                };
                            })(lastResult, map));
                        }
                    });

                    //不在线
                    $rootScope.Socket.on('OffLine', function(data) {
                        showMsg('设备当前不在线...');
                    });
                    //只是文本
                    $rootScope.Socket.on('PlainText', function(data) {});


                    $rootScope.Socket.on('connect_failed', function() {

                    });
                    $rootScope.Socket.on('disconnect', function() {
                        console.log('DisConnected from server!!');
                    });
                },
                subscribers: {

                },
                on: function(eventName, fn) {
                    for (var e in receiver.subscribers) {
                        if (eventName === e) {
                            receiver.subscribers[e] = fn;
                            return;
                        }
                    }
                    receiver.subscribers[eventName] = fn;
                },
                publish: function(eventName, data) {
                    for (var e in receiver.subscribers) {
                        if (eventName === e) {
                            var fn = receiver.subscribers[e];
                            fn(data);
                            return;
                        }
                    }
                }
            };
            return receiver;
        }
    ]);
});
